// cnpm install 安装后请执行 npx node-pre-gyp rebuild -C ./node_modules/canvas

const http = require('http');
const url = require('url');
const {createCanvas, loadImage, registerFont} = require('canvas');
registerFont('comicsans.ttf', {family: 'Comic Sans'});

const port = 3007;

const defaultColors = [
  'aliceblue',
  'antiquewhite',
  'aqua',
  'aquamarine',
  'azure',
  'beige',
  'bisque',
  'black',
  'blanchedalmond',
  'blue',
  'blueviolet',
  'brown',
  'burlywood',
  'cadetblue',
  'chartreuse',
  'chocolate',
  'coral',
  'cornflowerblue',
  'cornsilk',
  'crimson',
  'cyan',
  'darkblue',
  'darkcyan',
  'darkgoldenrod',
  'darkgray',
  'darkgreen',
  'darkgrey',
  'darkkhaki',
  'darkmagenta',
  'darkolivegreen',
  'darkorange',
  'darkorchid',
  'darkred',
  'darksalmon',
  'darkseagreen',
  'darkslateblue',
  'darkslategray',
  'darkslategrey',
  'darkturquoise',
  'darkviolet',
  'deeppink',
  'deepskyblue',
  'dimgray',
  'dimgrey',
  'dodgerblue',
  'firebrick',
  'floralwhite',
  'forestgreen',
  'fuchsia',
  'gainsboro',
  'ghostwhite',
  'gold',
  'goldenrod',
  'gray',
  'green',
  'greenyellow',
  'grey',
  'honeydew',
  'hotpink',
  'indianred',
  'indigo',
  'ivory',
  'khaki',
  'lavender',
  'lavenderblush',
  'lawngreen',
  'lemonchiffon',
  'lightblue',
  'lightcoral',
  'lightcyan',
  'lightgoldenrodyellow',
  'lightgray',
  'lightgreen',
  'lightgrey',
  'lightpink',
  'lightsalmon',
  'lightseagreen',
  'lightskyblue',
  'lightslategray',
  'lightslategrey',
  'lightsteelblue',
  'lightyellow',
  'lime',
  'limegreen',
  'linen',
  'magenta',
  'maroon',
  'mediumaquamarine',
  'mediumblue',
  'mediumorchid',
  'mediumpurple',
  'mediumseagreen',
  'mediumslateblue',
  'mediumspringgreen',
  'mediumturquoise',
  'mediumvioletred',
  'midnightblue',
  'mintcream',
  'mistyrose',
  'moccasin',
  'navajowhite',
  'navy',
  'oldlace',
  'olive',
  'olivedrab',
  'orange',
  'orangered',
  'orchid',
  'palegoldenrod',
  'palegreen',
  'paleturquoise',
  'palevioletred',
  'papayawhip',
  'peachpuff',
  'peru',
  'pink',
  'plum',
  'powderblue',
  'purple',
  'red',
  'rosybrown',
  'royalblue',
  'saddlebrown',
  'salmon',
  'sandybrown',
  'seagreen',
  'seashell',
  'sienna',
  'silver',
  'skyblue',
  'slateblue',
  'slategray',
  'slategrey',
  'snow',
  'springgreen',
  'steelblue',
  'tan',
  'teal',
  'thistle',
  'tomato',
  'turquoise',
  'violet',
  'wheat',
  'white',
  'whitesmoke',
  'yellow',
  'yellowgreen'
];


http.createServer(function (req, res) {
  if (req.url === '/favicon.ico') {
    return res.end();
  }

  const urlObj = url.parse(req.url, true);
  let pathname = urlObj.pathname;
  if (pathname.startsWith('/')) {
    pathname = pathname.substr(1);
  }
  if (pathname.endsWith('/')) {
    pathname = pathname.substr(0, pathname.length - 1);
  }

  var pathArr = pathname.split('/');
  console.log(urlObj);
  console.log(req.url);
  console.log('-----------');

  var params = urlObj.query;


  const size = pathArr[0].replace('X', 'x');
  const bgcolor = getColorByParam(pathArr[1], '#A7E59B');
  const color = getColorByParam(pathArr[2], '#777777');

  let width;
  let height;
  if (size && size.includes('x')) {
    const sizeArr = size.split('x');
    width = +sizeArr[0];
    height = +sizeArr[1];
  } else if (size && size.includes('*')) {
    const sizeArr = size.split('*');
    width = +sizeArr[0];
    height = +sizeArr[1];
  } else if (size) {
    width = +size;
    height = +size;
  } else {
    width = 300;
    height = 300;
  }


  let text;
  if (urlObj.query.text) {
    text = urlObj.query.text;
  } else {
    text = width + 'x' + height;
  }


  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext('2d');

  //绘制矩形
  ctx.fillStyle = bgcolor;
  ctx.fillRect(0, 0, width, height);

  //绘制文字
  const fontSize = getFontSize(width, height);
  ctx.font = fontSize + 'px "Comic Sans"';
  ctx.fillStyle = color;
  const m = ctx.measureText(text);
  ctx.fillText(text, width / 2 - m.width / 2, height / 2 + fontSize / 2);

  //测试文字区块位置
  //ctx.strokeStyle = 'blue';
  //ctx.strokeRect(width / 2 - m.width/2, height / 2 - 15, m.width, 30);


  const buf = canvas.toDataURL();
  const base64Data = buf.replace(/^data:image\/\w+;base64,/, '');
  const dataBuffer = Buffer.from(base64Data, 'base64');

  return res.end(dataBuffer);
}).listen(port);

function getFontSize(width, height) {
  const tmpWidth = Math.round(width / 10);
  const tmpHeight = Math.round(height / 10);
  let fontSize = tmpHeight < tmpWidth ? tmpHeight : tmpWidth;
  if (fontSize < 12) {
    fontSize = 12;
  }
  return fontSize;
}

function getColorByParam(param, defaultColor) {
  if (!param) {
    return defaultColor;
  } else if (param == 'rd') {
    return getRandomColor();
  } else if (defaultColors.indexOf(param) > -1) {
    return param;
  } else {
    return '#' + param;
  }
}

function getRandomColor() {
  let color = '#';
  for (let i = 0; i < 3; i++) {
    const hex = Math.floor(Math.random() * (255 + 1)).toString(16);
    color += (hex.length == 1 ? '0' + hex : hex);
  }
  return color;
}

console.log('server is ok on', 'http://127.0.0.1:3007');
